package ay.shadow.gateway.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class HomeController {

    // 首页
    @GetMapping("/")
    public String home() {
        return "home";
    }

    // 登录页面
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    // 登录成功后的仪表盘页面
    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        // 尝试从多个地方获取token
//        String token = extractToken(request);
        
//        if (token != null && jwtUtil.validateToken(token)) {
//            // token有效，从token中获取用户信息
//            String username = jwtUtil.getUsernameFromToken(token);
//            String role = jwtUtil.getRoleFromToken(token);
//
//            model.addAttribute("username", username);
//            model.addAttribute("roles", "ROLE_" + role);
//        } else {
            // 尝试从Spring Security上下文获取
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null) {
                model.addAttribute("username", authentication.getName());
                model.addAttribute("roles", authentication.getAuthorities());
            } else {
                model.addAttribute("username", "未登录用户");
                model.addAttribute("roles", "无权限");
            }
//        }
        
        return "dashboard";
    }

    // 处理表单登录的接口
    @PostMapping("/login")
    public String formLogin(@RequestParam String username, 
                           @RequestParam String password, 
                           Model model) {
        // 简单的用户验证逻辑
        if ("admin".equals(username) && "admin".equals(password)) {
            // 登录成功，重定向到仪表盘
            return "redirect:/dashboard";
        } else {
            // 登录失败，返回登录页面并显示错误信息
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }

    // 处理登出请求（GET方式，用于页面跳转）
    @GetMapping("/logout")
    public String logout() {
        // 重定向到首页
        return "redirect:/";
    }
}

